<?php


namespace App\LayAdmin\Controllers;


use App\Exceptions\ExceptionApi;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

trait TraitCRUD
{
//    protected $modelClass;

    protected function getModel(Request $request):Model{
        $id = $request->input('id');
        $data = $request->input('data');
        if($id==null && isset($data['id'])){
            $id = $data['id'];
        }
        $model = $this->modelClass::query()->where('id', '=', $id)->first();
        if(!$model){
            throw new ExceptionApi('资源不存在');
        }
        return $model;
    }

    public function delete(Request $request):Response{
        $model = $this->getModel($request);
        $msg = '删除失败';
        if($model->delete()){
            $msg = '删除成功';
        }
        return new Response(['msg'=>$msg, 'code'=>200]);
    }
}
